import router from "../router";
import {merge } from 'lodash-es'
import {Iframe} from "./type";
import {filterProps} from "../utils";
/**
 * useComponents
 * @description 打开跳转页面，并带回结果
 * @param { object } op - 配置对象
 * @returns { Promise<any> } - 返回一个Promise，用于接收从iframe传回的数据
 */
export function useComponents(op:Iframe): Promise<any> {
    return new Promise((resolve, reject) => {
        const defaultConfig={
            position:'fixed',
            top:'0',
            left:'0',
            width:'100%',
            height:'100%',
            background:'#fff',
            border:'none',
            zIndex:'1000'
        }
        const iframeConfig=merge({},defaultConfig,filterProps(op)) as Required<Iframe>
        const iframe = createIframe(iframeConfig);
        const title = getTitle(iframeConfig.src);
        history.pushState(null, "", "#useComponents");
        document.title = op.title || title || "";
        document.body.appendChild(iframe);
        //添加事件监听
        window.addEventListener("popstate", popstateHandler);
        window.addEventListener("message", messageHandler);
        //后退操作处理
        const popstateHandler = () => {
            closeIframe();
            resolve(null);
        };
        //接收消息处理
        const messageHandler = (event: MessageEvent) => {
            const data = event.data || {};
            //数据在业务中处理 这里不做解析
            resolve(data);
            closeIframe();
            history.back();
        };
        // 关闭iframe
        const closeIframe = () => {
            window.removeEventListener("popstate", popstateHandler);
            window.removeEventListener("message", messageHandler);
            if (iframe) {
                document.body.removeChild(iframe);
            }
        };
        // 组装iframe参数
        function createIframe(iframeConfig:Required<Iframe>) {
            const iframe = document.createElement("iframe");
            iframe.src = iframeConfig.src;
            iframe.style.position = iframeConfig.position;
            iframe.style.top = iframeConfig.top;
            iframe.style.left =iframeConfig.left;
            iframe.style.width = iframeConfig.width;
            iframe.style.height = iframeConfig.height;
            iframe.style.background = iframeConfig.background;
            iframe.style.border = iframeConfig.border;
            iframe.style.zIndex =iframeConfig.zIndex;
            return iframe;
        }
        // 获取title
        function getTitle(src: string) {
            const route = router.getRoutes().find((item) => item.path === src.split("?")[0]);
            return route?.meta?.title || "";
        }
    });
}

/**
 * 向父窗口发送消息 此方法和上述方法配对使用
 * @param { object } obj - 消息对象
 */
export function postMsg(obj: any = {}) {
    window.parent &&
    window.parent.postMessage(
        {
            action: "useComponents:data",
            data: obj,
        },
        "*"
    );
}